//
//  DetailViewController.m
//  PTravel
//
//  Created by dllo on 15/11/18.
//  Copyright © 2015年 李涵. All rights reserved.
//

#import "DetailViewController.h"

@interface DetailViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (retain, nonatomic)YYCycleScrollView *cycleScrollView;//轮播图scrollView
@property (retain, nonatomic)NSMutableArray *slideArr;//轮播图数组
@property (retain, nonatomic)UITableView *mytableView;
@property (retain, nonatomic)NSMutableArray *tableViewArr;//tableView组
@property (retain, nonatomic)UIImageView *tempImageView;
@property (retain, nonatomic)UICollectionView *myCollection;
@property (retain, nonatomic)NSMutableArray *hotCityArr;

@property (retain, nonatomic)UILabel *label;
@property (retain, nonatomic)UILabel *labell;
@property (retain, nonatomic)UILabel *labelll;
@property (retain, nonatomic)UIButton *totalLabel;
@property (retain, nonatomic)UIButton *totalLabell;
@property (copy, nonatomic)NSString *str;

@property (retain, nonatomic)UIView *aView;

@end

@implementation DetailViewController

- (void)dealloc
{
    [_cycleScrollView release];
    [_slideArr release];
    [_myCollection release];
    [_mytableView release];
    [_tempImageView release];
    [_tableViewArr release];
    [_hotCityArr release];
    [_label release];
    [_labell release];
    [_labelll release];
    [_smallDic release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    //隐藏tarBar
    NSArray *temp = self.tabBarController.view.subviews;
    UIView *view = temp[2];
    view.frame = CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, self.view.frame.size.height);
    //背景图片透明
    UIImage *image = [UIImage imageNamed:@"bg_clear.jpg"];
    [self.navigationController.navigationBar setBackgroundImage:image
                                                  forBarMetrics:UIBarMetricsDefault];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setShadowImage:image];
    NSString *sql = @"CREATE TABLE traveledCountry (country_id INTEGER PRIMARY KEY AUTOINCREMENT,cnname TEXT NOT NULL)";
    [[DataBaseHandle shareDataBase] createTableSql:sql];
    NSMutableArray *arr = [[DataBaseHandle shareDataBase] selectDataTableSql:@"select * from traveledCountry"];
    
    NSMutableArray *array = [NSMutableArray array];
    for (Country *country in arr) {
        [array addObject:[NSString stringWithFormat:@"%ld",country.id]];
    }
    if (![array containsObject:[NSString stringWithFormat:@"%ld",self.cityId]]) {
        NSLog(@"111111");
        //右收藏
        UIImage *likeImage = [UIImage imageNamed:@"iconfont-collect_article"];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:likeImage style:UIBarButtonItemStylePlain target:self action:@selector(collectAction)];
    }else{
         NSLog(@"2222222222");
        //右收藏
        UIImage *likeImage = [UIImage imageNamed:@"iconfont-shoucang1"];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:likeImage style:UIBarButtonItemStylePlain target:self action:@selector(collectAction)];
    }
    
    //夜间模式判断
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor:) name:@"night" object:nil];
}

- (void)changeColor:(NSNotificationCenter *)notification
{
    self.view.backgroundColor = CELLCOLOR;
    self.myCollection.backgroundColor = CELLCOLOR;
    [self.myCollection reloadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.labelll = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    self.labell = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
    
    self.totalLabel = [[UIButton alloc] initWithFrame:CGRectMake(BOUNDS.size.width-110, 10, 100, 30)];
    self.totalLabell = [[UIButton alloc] initWithFrame:CGRectMake(BOUNDS.size.width-110, 10, 100, 30)];
    self.view.backgroundColor = [UIColor cyanColor];
    
    self.view.backgroundColor = CELLCOLOR;
    
    //左箭头
    UIImage *BackImage = [UIImage imageNamed:@"btn_webview_back.png"];
    BackImage = [BackImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:BackImage style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    self.navigationItem.title = [self.smallDic objectForKey:@"cname"];
    

    //self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:likeImage style:UIBarButtonItemStylePlain target:self action:@selector(collectAction)];
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    [self getdata];
}

#pragma mark === 返回按钮
- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark === 收藏按钮
- (void)collectAction
{
    NSString *sql = @"CREATE TABLE traveledCountry (country_id INTEGER PRIMARY KEY AUTOINCREMENT,cnname TEXT NOT NULL)";
    NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO TraveledCountry (country_id, cnname) VALUES ('%ld', '%@')",(long)self.cityId,[self.smallDic objectForKey:@"cnname"]];
    [[DataBaseHandle shareDataBase] createTableSql:sql];
    NSMutableArray *arr = [[DataBaseHandle shareDataBase] selectDataTableSql:@"select * from traveledCountry"];

    NSMutableArray *array = [NSMutableArray array];
    for (Country *country in arr) {
        [array addObject:country.cnname];
    }
    if (![array containsObject:[self.smallDic objectForKey:@"cnname"]]) {
        //右收藏
        UIImage *likeImage = [UIImage imageNamed:@"iconfont-shoucang1"];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:likeImage style:UIBarButtonItemStylePlain target:self action:@selector(collectAction)];
        [[DataBaseHandle shareDataBase] insertData:insertSql];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
            
            
        }];
        [self dismissViewControllerAnimated:YES completion:^{
            
            
        }];
    }else{
        
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您已经收藏过了" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
            
            
        }];
        [self dismissViewControllerAnimated:YES completion:^{
            
            
        }];
    }
}

#pragma mark === 轮播图方法及数据请求
- (void)getdata
{
    
    self.hotCityArr = [NSMutableArray array];
    self.slideArr = [NSMutableArray array];
    self.tableViewArr = [NSMutableArray array];
    self.cycleScrollView = [[YYCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, BOUNDS.size.width, BOUNDS.size.height/2-100) animationDuration:2.0];
    self.cycleScrollView.contentMode = UIViewContentModeScaleAspectFill;
    [_cycleScrollView release];
    if (self.cityId == 62) {
        self.str = @"http://open.qyer.com/qyer/footprint/city_detail?city_id=62&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=38.88276672342587&lon=121.5400238037919&page=1&track_app_channel=App%2520Store&track_app_version=6.8.2&track_device_info=iPhone7%2C2&track_deviceid=94E2CF74-5FF7-49B9-8D69-620BF45F65A9&track_os=ios%25209.1&v=1";
    }else{
        
        self.str = [NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/country_detail?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&country_id=%ld&lat=38.88261992787411&lon=121.5395075491762&page=1&track_app_channel=App%%2520Store&track_app_version=6.8.2&track_device_info=iPhone7%%2C2&track_deviceid=94E2CF74-5FF7-49B9-8D69-620BF45F65A9&track_os=ios%%25209.1&v=1", self.cityId];
    }
    [AppTools getAFN:self.str block:^(id result) {
        NSMutableDictionary *bigDic = result;
        self.smallDic = [bigDic objectForKey:@"data"];
       
        //轮播图
        self.slideArr = [self.smallDic objectForKey:@"photos"];
        NSMutableArray *viewArray = [[NSMutableArray alloc] init];
        for (NSString *str in self.slideArr) {
            self.tempImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, +200, BOUNDS.size.width, BOUNDS.size.height/2-100)];
            NSURL *url = [NSURL URLWithString:str];
            [self.tempImageView sd_setImageWithURL:url placeholderImage:IMAGE];
            
            self.tempImageView.contentMode = UIViewContentModeScaleAspectFill;
            self.tempImageView.clipsToBounds = true;
            [viewArray addObject:self.tempImageView];
            [_tempImageView release];
            
        }
        for (int i = 0; i < self.slideArr.count; i++) {
        }
        [self.cycleScrollView setFetchContentViewAtIndex:^UIView *(NSInteger(pageIndex)) {
            return [viewArray objectAtIndex:pageIndex];
        }];
        [self.cycleScrollView setTotalPagesCount:^NSInteger{
            return self.slideArr.count;
        }];
        [self.cycleScrollView setTapActionBlock:^(NSInteger(pageIndex)) {
            
            NSLog(@"点击的相关的页面%ld",(long)pageIndex);
            
        }];
        
        //轮播图上的控件
        UILabel *cnname = [[UILabel alloc] initWithFrame:CGRectMake(20, self.cycleScrollView.frame.size.height/2+6, 200, 25)];
        cnname.text = [self.smallDic objectForKey:@"cnname"];
        cnname.textColor = [UIColor whiteColor];
        cnname.font = [UIFont systemFontOfSize:23];
        [self.cycleScrollView addSubview:cnname];
        
        UILabel *enname = [[UILabel alloc] initWithFrame:CGRectMake(20, cnname.frame.origin.y+25, 200, 25)];
        enname.text = [self.smallDic objectForKey:@"enname"];
        enname.textColor = [UIColor colorWithRed:109 green:109 blue:109 alpha:0.7];
        enname.font = [UIFont systemFontOfSize:20];
        [self.cycleScrollView addSubview:enname];
        [enname release];
        
        UILabel *entryCont = [[UILabel alloc] initWithFrame:CGRectMake(20, enname.frame.origin.y+40, BOUNDS.size.width-40, 40)];
        entryCont.text = [self.smallDic objectForKey:@"entryCont"];
        entryCont.textColor = [UIColor colorWithRed:144 green:144 blue:144 alpha:0.7];
        entryCont.font = [UIFont systemFontOfSize:15];
        entryCont.numberOfLines = 0;
        [self.cycleScrollView addSubview:entryCont];
        [entryCont release];

        
        //热门城市数据请求
        NSMutableArray *hotArr = [self.smallDic objectForKey:@"hot_city"];
        for (NSMutableDictionary *dic in hotArr) {
            HotCity *hotCity = [[HotCity alloc] init];
            [hotCity setValuesForKeysWithDictionary:dic];
            [self.hotCityArr addObject:hotCity];
            [hotCity release];
        }
        
        //超值自由行数据请求
        NSMutableArray *arr = [self.smallDic objectForKey:@"new_discount"];
        for (NSMutableDictionary *dic in arr) {
            New_discount *dis = [[New_discount alloc] init];
            [dis setValuesForKeysWithDictionary:dic];
            [self.tableViewArr addObject:dis];
        }
        

        
        //collection
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        self.myCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, -44-200, BOUNDS.size.width, BOUNDS.size.height+49+200) collectionViewLayout:layout];
        self.myCollection.contentInset = UIEdgeInsetsMake(200, 8, 8, 8);
        layout.headerReferenceSize = CGSizeMake(BOUNDS.size.width, 40);
        self.myCollection.delegate = self;
        self.myCollection.dataSource = self;
        [_myCollection release];
        [layout release];
        
        //注册不同的cell
        [self.myCollection registerClass:[CountryDetailCollectionViewCell class] forCellWithReuseIdentifier:@"CountryDetailCollectionViewCell"];
        [self.myCollection registerClass:[HotCountryCollectionViewCell class] forCellWithReuseIdentifier:@"HotCountryCollectionViewCell"];
        [self.myCollection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        [self.myCollection registerClass:[ZCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ZCollectionReusableView"];
        
        self.aView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BOUNDS.size.width, BOUNDS.size.height/2-100)];
        [self.view addSubview:self.aView];
        
        self.myCollection.backgroundColor = CELLCOLOR;
        self.myCollection.showsVerticalScrollIndicator = NO;
        [self.view addSubview:self.myCollection];
        //self.myCollection.bounces = NO;
    }];
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //创建头部区域
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"ZCollectionReusableView" forIndexPath:indexPath];
        headView.backgroundColor = CELLCOLOR;
        if (indexPath.section == 0) {
            [headView addSubview:self.labelll];
            return headView;
        }
        if (indexPath.section == 1) {
            [self.totalLabel setTitle:@"查看全部 ＞" forState:UIControlStateNormal];
            [self.totalLabel setTitleColor:TEXTCOLOR forState:UIControlStateNormal];
            [self.totalLabel addTarget:self action:@selector(cityAction) forControlEvents:UIControlEventTouchUpInside];
            self.labell.text =[NSString stringWithFormat:@"%@城市", [self.smallDic objectForKey:@"cnname"]];
            self.labell.textColor = TEXTCOLOR;
            [headView addSubview:self.labell];
            [headView addSubview:self.totalLabel];
            return headView;
            
        }else{
            if (self.tableViewArr.count != 0) {
                [self.totalLabell setTitle:@"查看全部 ＞" forState:UIControlStateNormal];
                [self.totalLabell setTitleColor:TEXTCOLOR forState:UIControlStateNormal];
                [self.totalLabell addTarget:self action:@selector(freeAction) forControlEvents:UIControlEventTouchUpInside];
                self.label.text =@"超值自由行";
                self.label.textColor = TEXTCOLOR;
                [headView addSubview:self.totalLabell];
                [headView addSubview:self.label];
                return headView;
            }
            return headView;
        }
        

        
    }else{
        UICollectionReusableView *footView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
        return footView;
    }
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 3;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return self.hotCityArr.count;
    }else{
        return self.tableViewArr.count;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        [cell addSubview:self.cycleScrollView];

        cell.backgroundColor = CELLCOLOR;
        return cell;
    }else if (indexPath.section == 1) {
        HotCountryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotCountryCollectionViewCell" forIndexPath:indexPath];
        cell.hotCountry = [self.hotCityArr objectAtIndex:indexPath.item];
        cell.backgroundColor = CELLCOLOR;
        return cell;
    }else{
        CountryDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CountryDetailCollectionViewCell" forIndexPath:indexPath];
        cell.discount = [self.tableViewArr objectAtIndex:indexPath.row];
        cell.backgroundColor = CELLCOLOR;
        return cell;
    }
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(BOUNDS.size.width, BOUNDS.size.height/2-100);
    }else if (indexPath.section == 1) {
        return CGSizeMake(BOUNDS.size.width/2-15, 105);
    }else{
        return CGSizeMake(BOUNDS.size.width, 80);
    }
}


#pragma mark === 全部板块点击跳转
- (void)cityAction
{
    TotalCityViewController *city = [[TotalCityViewController alloc] init];
    [self.navigationController pushViewController:city animated:YES];
    city.countryId = self.cityId;
    [city release];
}
- (void)freeAction
{
    TotalFreeViewController *free = [[TotalFreeViewController alloc] init];
    //free.navigationController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:free animated:YES];
    free.countryId = self.cityId;
    [free release];
    
}

#pragma mark === 下拉变大
//-(void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    //刚开始y的偏移量初始值就是-264
//    NSLog(@"y1 === %f",scrollView.contentOffset.y);
//    CGFloat y = scrollView.contentOffset.y;//加上导航栏高度,第一次是-200
//    NSLog(@"y2 === %f",y);
//    
//    if (y < -200) {
//        CGRect frame1 = self.tempImageView.frame;
//        frame1.origin.y = -y;//偏移了多少,
//        frame1.size.height = BOUNDS.size.height/2 -y;//tablview向下偏移了多少,高度就是多少
//        self.tempImageView.frame = frame1;
//        
//        
//    }
//    
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
